<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="128px"
      v-loading="formLoading"
    >
      <el-form-item v-if="formType === 'update'" label="配送计划编号" prop="planCode" disabled>
        <el-input v-model="formData.planCode" placeholder="请输入服务用具配送计划编号" disabled />
      </el-form-item>
      <el-form-item label="关联航班" prop="flightNo">
        <el-input v-model="formData.flightNo" placeholder="请输入关联航班" />
      </el-form-item>
      <el-form-item label="餐具名称" prop="tablewareId">
        <el-select
          placeholder="请选择餐具"
          filterable
          class="!w-240px"
          v-model="formData.tablewareId"
          :filter-method="getSimpleList"
        >
          <el-option
            v-for="simple in SimpleList"
            :key="simple.id"
            :label="simple.name"
            :value="simple.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="餐具数量" prop="tablewareQty">
        <el-input-number
          v-model="formData.tablewareQty"
          :min="0"
          controls-position="right"
          placeholder="请输入餐具数量(个)"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="配送状态" prop="distStatus">
        <el-select v-model="formData.distStatus" placeholder="请选择配送状态" class="!w-220px">
          <el-option
            v-for="item in getIntDictOptions(DICT_TYPE.ACM_TABLEWARE_DIST_STATUS)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配送计划时间" prop="expireDate">
        <el-date-picker
          v-model="formData.expireDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          type="textarea"
          :rows="4"
          maxlength="400"
          show-word-limit
          v-model="formData.remarks"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        @click="submitForm"
        type="primary"
        v-if="formType === 'create'"
        :disabled="formLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { TablewareDistPlanApi, TablewareDistPlanVO } from '@/api/pplan/tablewaredistplan'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { TablewareApi, TablewareVO } from '@/api/pplan/tableware'

/** 机供品餐具配送计划 表单 */
defineOptions({ name: 'TablewareDistPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  planCode: undefined,
  flightNo: undefined,
  tablewareId: undefined,
  tablewareQty: undefined,
  distStatus: undefined,
  startDate: undefined,
  endDate: undefined,
  remarks: undefined,
  expireDate: []
})
const formRules = reactive({
  planCode: [{ required: true, message: '餐具配送计划编号不能为空', trigger: 'blur' }],
  flightNo: [{ required: true, message: '关联航班不能为空', trigger: 'blur' }],
  tablewareId: [{ required: true, message: '餐具不能为空', trigger: 'blur' }],
  tablewareQty: [{ required: true, message: '餐具数量(个)不能为空', trigger: 'blur' }],
  distStatus: [{ required: true, message: '配送状态不能为空', trigger: 'change' }],
  startDate: [{ required: true, message: '计划有效期开始不能为空', trigger: 'blur' }],
  endDate: [{ required: true, message: '计划有效期结束不能为空', trigger: 'blur' }],
  expireDate: [{ required: true, message: '配送计划时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

// 新增：备份完整的餐具列表
const tablewareAllList = ref<TablewareVO[]>([])

/** 加载完整的餐具列表（仅加载一次） */
const loadAllTablewares = async () => {
  if (tablewareAllList.value.length > 0) return tablewareAllList.value
  const data = await TablewareApi.getTablewareSimpleList('')
  tablewareAllList.value = data
  return data
}

/** 修改：获取机供品精简列表（确保已选餐具在列表中） */
const SimpleList = ref<TablewareVO[]>([])
const getSimpleList = async (query?: string) => {
  // 确保已加载完整餐具列表
  await loadAllTablewares()

  // 1. 获取已选的餐具ID
  const selectedTablewareId = formData.value.tablewareId

  // 2. 筛选已选的餐具（如果有）
  const selectedTablewares: TablewareVO[] = []
  if (selectedTablewareId) {
    const selected = tablewareAllList.value.find((item) => item.id === selectedTablewareId)
    if (selected) {
      selectedTablewares.push(selected)
    }
  }

  // 3. 根据查询条件过滤数据
  let filteredTablewares: TablewareVO[] = []
  if (!query) {
    // 无查询时：取前200条
    filteredTablewares = [...tablewareAllList.value].slice(0, 200)
  } else {
    // 有查询时：按名称过滤
    filteredTablewares = tablewareAllList.value.filter((item) =>
      item.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 4. 合并并去重
  SimpleList.value = Array.from(
    new Map([...selectedTablewares, ...filteredTablewares].map((item) => [item.id, item])).values()
  )
  return SimpleList.value
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 先加载完整的餐具列表
  await loadAllTablewares()
  // 初始化显示列表
  await getSimpleList('')

  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据并补全已选餐具
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TablewareDistPlanApi.getTablewareDistPlan(id)
      formData.value.expireDate = [formData.value.startDate, formData.value.endDate]
      // 确保已选餐具在列表中
      await getSimpleList('')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TablewareDistPlanVO
    if (formType.value === 'create') {
      await TablewareDistPlanApi.createTablewareDistPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await TablewareDistPlanApi.updateTablewareDistPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planCode: undefined,
    flightNo: undefined,
    supplyId: undefined,
    tablewareQty: undefined,
    distStatus: undefined,
    startDate: undefined,
    endDate: undefined,
    remarks: undefined,
    expireDate: []
  }
  formRef.value?.resetFields()
}
</script>
